package com.yy.ant.sys.controller;


import java.util.ArrayList;
import java.util.List;

import com.yy.ant.sys.entity.User;
import com.yy.ant.sys.entity.UserRole;
import com.yy.ant.sys.service.IUserRoleService;
import com.yy.ant.sys.service.IUserService;
import com.yy.utils.JwtUtils;
import com.yy.utils.SessionUtil;
import io.jsonwebtoken.Claims;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestHeader;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.yy.ant.sys.entity.Resources;
import com.yy.ant.sys.entity.RoleResources;
import com.yy.ant.sys.service.IResourcesService;
import com.yy.ant.sys.service.IRoleResourcesService;
import com.yy.model.EleTree;
import com.yy.model.Menu;
import com.yy.model.ResultMsg;
import com.yy.model.ResultTable;
import com.yy.model.enums.ResultEnum;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author liyingying
 * @since 2019-12-20
 */
@RestController
@RequestMapping("/sys/resources")
public class ResourcesController {
	
	@Autowired
	private IResourcesService iResourcesService;


	@Autowired
	private IUserRoleService iUserRoleService;

	@Autowired
	private IRoleResourcesService iRoleResourcesService;
	@Autowired
	private IUserService iUserService;
	@RequestMapping(value = "/tree")
    public List<Menu> list(@RequestHeader("token") String token,@RequestParam(value = "types", required = false) String types) {
		ResultMsg resultMsg1= JwtUtils.validateJWT(token);
		if (!resultMsg1.isSuccess()){
			return null;
		}
		Claims claims= (Claims) resultMsg1.getData();
		User sysUser = iUserService.getById(claims.getId());
        List<Menu> list = iResourcesService.tree("0",sysUser);
        return list;
    }
	
	/**
	 * 分页查询
	 * @param str
	 * @param page
	 * @param limit
	 * @return
	 */
	@RequestMapping(value = "/listPage")
	public ResultTable<Resources> listPage(@RequestParam(value = "str",required = false) String str,
			@RequestParam(value = "page") String page,@RequestParam(value = "limit") String limit){
		JSONObject jsonObject=JSONObject.parseObject(str);
		QueryWrapper<Resources> queryWrapper=new QueryWrapper<Resources>();
		if (jsonObject!=null) {
			if (StringUtils.isNotEmpty(jsonObject.getString("startTime"))&& StringUtils.isNotEmpty(jsonObject.getString("endTime"))) {
				queryWrapper.between("createtime", jsonObject.getString("startTime"), jsonObject.getString("endTime"));
			}
			if (StringUtils.isNotEmpty(jsonObject.getString("name"))) {
				queryWrapper.like("name", jsonObject.getString("name"));
			}
		}
		
		IPage<Resources> iPage=iResourcesService.page(new Page<>(Integer.valueOf(page),Integer.valueOf(limit)),queryWrapper);
		ResultTable<Resources> uResultTable=new ResultTable<Resources>();
		uResultTable.setCount(iPage.getTotal());
		uResultTable.setData(iPage.getRecords());
		return uResultTable;
	}
	/**
	 * 分页查询
	 * @return
	 */
	@RequestMapping(value = "/eleTreeAll")
	public ResultTable<EleTree> eleTreeAll(){
		List<Resources> iPage=iResourcesService.list();
		List<EleTree> list=new ArrayList<EleTree>();
		for (Resources o:iPage){
            if (o.getPid() == 0) {
                EleTree m1 = new EleTree();
                m1.setId(o.getId());
                m1.setLabel(o.getTitle());
                list.add(m1);
            }
        }
		for (EleTree menu : list) {
            menu.setChildren(getChildEleTree(menu.getId(), iPage));
        }
		
		ResultTable<EleTree> uResultTable=new ResultTable<EleTree>();
		uResultTable.setData(list);
		return uResultTable;
	}
	
	/**
	 * 分页查询
	 * @return
	 */
	@RequestMapping(value = "/listAll")
	public ResultTable<Resources> listAll(@RequestHeader("token") String token){
		ResultMsg resultMsg1= JwtUtils.validateJWT(token);
		ResultTable<Resources> uResultTable=new ResultTable<Resources>();
		if (!resultMsg1.isSuccess()){
			uResultTable.setMsg(resultMsg1.getMsg());
			return uResultTable;
		}
		Claims claims= (Claims) resultMsg1.getData();
		User sysUser = iUserService.getById(claims.getId());
		List<Resources> iPage=null;
		if (SessionUtil.getAdmin(sysUser.getUname())) {
			iPage=iResourcesService.list();
			uResultTable.setData(iPage);
			return uResultTable;
		}
		List<Long> list=new ArrayList<>();
		List<UserRole> userRoles=iUserRoleService.list(new QueryWrapper<UserRole>().eq("user_id",sysUser.getId()));
		for (UserRole userRole:userRoles){
			list.add(userRole.getRoleId());
		}
		List<Long> list1=new ArrayList<>();
		if (list!=null&&list.size()>0){
			List<RoleResources> roleResources=iRoleResourcesService.list(new QueryWrapper<RoleResources>().in("role_id",list));
			for (RoleResources o:roleResources){
				list1.add(o.getResourcesId());
			}
		}

		if (list1!=null&&list1.size()>0){
			iPage=iResourcesService.list(new QueryWrapper<Resources>().in("id",list1));
		}

		uResultTable.setData(iPage);
		return uResultTable;
	}
	/**
	 * 根据ID查询数据
	 * @param id
	 * @return
	 */
	@RequestMapping(value = "/byId")
	public ResultMsg byId(@RequestParam(value = "id")String id) {
		ResultMsg resultMsg=new ResultMsg();
		Resources b=iResourcesService.getById(id);
		if (b!=null) {
			resultMsg.setData(b);
			resultMsg.setSuccess(true);
			resultMsg.setMsg(ResultEnum.sucess_create_failed.getMsg());
		}else {
			resultMsg.setMsg(ResultEnum.error_create_failed.getMsg());
		}
		
		return resultMsg;
	}
	
	/**
	 * 新增
	 * @param str
	 * @return
	 */
	@RequestMapping(value = "/add")
	public ResultMsg add(@RequestParam(value = "str",required = false)String str) {
		Resources resources=JSON.parseObject(str, Resources.class);
		ResultMsg resultMsg=new ResultMsg();
		boolean b=iResourcesService.save(resources);
		if (b) {
			resultMsg.setSuccess(true);
			resultMsg.setMsg(ResultEnum.sucess_create_failed.getMsg());
		}else {
			resultMsg.setMsg(ResultEnum.error_create_failed.getMsg());
		}
		
		return resultMsg;
	}
	/**
	 * 删除
	 * @param str
	 * @return
	 */
	@RequestMapping(value = "/delete")
	public ResultMsg delete(@RequestParam(value = "str",required = false)String str) {
		List<Long> ids = new ArrayList<>();
        String[] id = str.split(",");
        for (int i = 0; i < id.length; i++) {
        	if (StringUtils.isNotEmpty(id[i])) {
        		ids.add(Long.valueOf(id[i]));
			}
        }
        ResultMsg resultMsg=new ResultMsg();
        boolean b=iResourcesService.removeByIds(ids);
		if (b) {
			resultMsg.setSuccess(true);
			resultMsg.setMsg(ResultEnum.sucess_delete_failed.getMsg());
		}else {
			resultMsg.setMsg(ResultEnum.error_delete_failed.getMsg());
		}
		return resultMsg;
	}
	
	
	
	/**
	 * 修改
	 * @param str
	 * @return
	 */
	@RequestMapping(value = "/update")
	public ResultMsg update(@RequestParam(value = "str",required = false)String str) {
		Resources resources=JSON.parseObject(str, Resources.class);
		ResultMsg resultMsg=new ResultMsg();
        boolean b=iResourcesService.updateById(resources);
        if (b) {
        	resultMsg.setSuccess(true);
			resultMsg.setMsg(ResultEnum.sucess_update_failed.getMsg());
		}else {
			resultMsg.setMsg(ResultEnum.error_update_failed.getMsg());
		}
		return resultMsg;
	}
	/**
     * 递归查找子菜单树（eleTree）
     *
     * @param id
     *            当前菜单id
     * @param rootMenu
     *            要查找的列表
     * @return
     */
    private List<EleTree> getChildEleTree(Long id, List<Resources> rootMenu) {
        // 子菜单
        List<EleTree> childList = new ArrayList<>();
        for (Resources o : rootMenu) {
            // 遍历所有节点，将父菜单id与传过来的id比较
            if (StringUtils.isNotBlank(String.valueOf(o.getId()))) {
                if (id==o.getPid()) {
                    EleTree m1 = new EleTree();
                    m1.setId(o.getId());
                    m1.setLabel(o.getTitle());
                    childList.add(m1);
                }
            }
        }
        // 把子菜单的子菜单再循环一遍
        for (EleTree menu : childList) {
            // 递归
            menu.setChildren(getChildEleTree(menu.getId(), rootMenu));
        }
        // 递归退出条件
        if (childList.size() == 0) {
            return null;
        }
        return childList;
    }

}
